<template>
  <div class="settlement-report-list table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :maxNum="6" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList" fromLocation="结算报告" :exportInfo="exportInfo" :seachData="seachData" :checkedList="selectIds">
        <template #headerLeft>
          <a-space>
            <a-button type="primary" size="medium" @click="openChooseProductDialog">手动设置产品SKU</a-button>
            <a-button type="primary" size="medium" @click="openShowUserDialog">手动设置运营</a-button>
            <div class="flex-c">
              <a-select v-model="updateSumType" value-key="value" allow-search allow-clear style="width: 140px" placeholder="选择汇总类型">
                <a-option v-for="(item, index) in sumTypesList" :key="index" :value="item">{{ item.label }}</a-option>
              </a-select>
              <a-button type="outline" size="medium" @click="onUpdateSumType">设置汇总类型</a-button>
            </div>
            <a-checkbox v-model="isNotSalesman" @change="searchByVal(filterData)">未绑定运营</a-checkbox>
            <a-checkbox v-model="isNotSumType" @change="searchByVal(filterData)">未汇总类型</a-checkbox>
            <p class="warningColor">对于即有分配额，又有运营的情况，统计分配额项目到汇总里面</p>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-singe-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            :data="tableList"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :bordered="{ headerCell: true }"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="市场" :width="50" fixed="left">
                <template #cell="{ record }">
                  <p :class="{ warningColor: !$extract(marketPlaceList[record.marketplace_id], 'code') }">
                    {{ $extract(marketPlaceList[record.marketplace_id], 'code') || record.marketplace_id }}
                  </p>
                </template>
              </a-table-column>
              <a-table-column title="店铺" :width="160" fixed="left">
                <template #cell="{ record }">
                  <template v-if="record.shop_name">
                    <TextLimit :rows="2" :val="record.shop_name" />
                  </template>
                  <div v-else>
                    <TextLimit class="warningColor" :rows="1" :val="oneShopName(record)" />
                    <p style="font-size: 10px; color: rgb(197, 196, 196)">如果市场确认无误，可忽略</p>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="结算ID" :width="100" data-index="settlement_id" fixed="left" />
              <a-table-column title="汇总类型" :width="80" data-index="sum_type_name" fixed="left" />
              <a-table-column title="币种" :width="60" data-index="currency" fixed="left" />
              <a-table-column title="金额" :width="100" data-index="amount" fixed="left" align="right" :sortable="sortable" />
              <a-table-column title="运营" :width="70" data-index="salesman_name" fixed="left" />
              <a-table-column title="金额说明" data-index="amount_Description" :width="160" fixed="left">
                <template #cell="{ record }">
                  <TextLimit :val="record.amount_Description" />
                </template>
              </a-table-column>
              <a-table-column title="金额分配" data-index="alloc_item_summary" :width="250">
                <template #cell="{ record }">
                  <a-button v-if="record.need_alloc" style="margin-right: 4px" size="mini" type="outline" :status="allocItemStatus(record) ? 'success' : undefined" @click="onShowAllocDialog(record)">分配</a-button>
                  <span class="alloc_item_summary">{{ record.alloc_item_summary }}</span>
                </template>
              </a-table-column>
              <a-table-column title="预留金?" data-index="reserved_status" :width="70">
                <template #cell="{ record }">
                  <span v-if="(record.sum_type === 'LAST_RESERVED_AMOUNT' || record.sum_type === 'THIS_RESERVED_AMOUNT') && (record.reserved_status === 1 || record.reserved_status === 3)"> 是 </span>
                </template>
              </a-table-column>
              <a-table-column title="CNY汇率" data-index="cny_rate" :width="100" align="right" :sortable="sortable" />
              <a-table-column title="CNY" data-index="cny_amount" :width="100" :sortable="sortable" align="right">
                <template #cell="{ record }">
                  <span>{{ record.cny_amount ? record.cny_amount.toFixed(2) : null }}</span>
                </template>
              </a-table-column>
              <a-table-column title="USD汇率" data-index="usd_rate" :width="100" align="right" :sortable="sortable" />
              <a-table-column title="USD" data-index="usd_amount" :width="100" :sortable="sortable" align="right">
                <template #cell="{ record }">
                  <span>{{ record.usd_amount ? record.usd_amount.toFixed(2) : null }}</span>
                </template>
              </a-table-column>
              <a-table-column title="结算开始" data-index="settlement_start_date" :width="180" />
              <a-table-column title="结算结束" data-index="settlement_end_date" :width="180" />
              <a-table-column title="发布时间" data-index="posted_Date_Time" :width="180" />
              <a-table-column title="订单号" data-index="order_Id" :width="120" />
              <a-table-column title="订单ItemCode" data-index="order_Item_Code" :width="120" />
              <a-table-column title="履约方式" data-index="fulfillment_Id" :width="70" />
              <a-table-column title="SellerSKU" data-index="sku" :width="120" />
              <a-table-column title="产品SKU" data-index="product_sku" :width="120" />
              <a-table-column title="ASIN" data-index="asin" :width="100" />
              <a-table-column title="交易类型" data-index="transaction_type" :width="80" />
              <a-table-column title="金额类型" data-index="amount_Type" :width="80" />
              <a-table-column title="商品数量" data-index="quantity_purchased" :width="70" />
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.currentPage" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 设置运营 -->
  <ChooseUser v-if="showUserDialog" title="设置所属运营" label="所属运营" :list="userList" :multiple="false" :isShow="showUserDialog" :isRequired="true" :value-obj="true" @closed="showUserDialog = false" @success="editSales" />
  <!-- 设置产品 -->
  <ChooseProduct v-if="showChooseProductDialog" title="搜索产品" :isShow="showChooseProductDialog" @closed="showChooseProductDialog = false" @success="chooseProduct" />

  <!-- 金额分配 -->
  <a-modal title="金额分配" title-align="start" v-if="allocDialog.show" v-model:visible="allocDialog.show" ok-text="保存分配" :width="900" top="8vh" :mask-closable="false" :on-before-ok="onReFeeAlloc" @cancel="allocDialog.show = false">
    <a-alert style="margin-bottom: 10px" type="normal" :closable="false" :show-icon="false">
      <h1 style="font-size: 20px; font-weight: bold">{{ allocDialog.item.sum_type_name }}:{{ allocDialog.item.amount }} {{ allocDialog.item.currency }}</h1>
      <p>默认情况下，系统会根据待分配金额当前结算单中销量比例来自动扣减相应的费用，对于费用返回，则是根据扣减分配来自动对冲。</p>
    </a-alert>
    <a-table class="table-normal-line" :scroll="{ y: 'calc(84vh - 340px)' }" :loading="allocDialog.loading" :data="allocDialog.allow_items" size="mini" :ok-loading="allocDialog.submitLoading" :bordered="false" :pagination="false">
      <template #columns>
        <a-table-column data-index="sort" title="业务员">
          <template #cell="{ record }">
            <p>{{ record.salesman_name }}</p>
          </template>
        </a-table-column>
        <a-table-column data-index="sort" title="分配金额" align="right">
          <template #cell="{ record }">
            <a-input-number v-model="record.alloc_amount" :style="{ width: '250px' }" mode="button" />
          </template>
        </a-table-column>
      </template>
    </a-table>
    <div class="flex-c-sb" style="margin-top: 20px">
      <div>
        <template v-if="allocDialog.salesamountList.length > 0">
          <div>
            <a-button @click="onAutoAlloc(1)" size="small">按业务员（本月本店）销售额比例分配</a-button>
          </div>
          <div style="margin-top: 10px">
            <a-button @click="onAutoAlloc(2)" size="small">按业务员（本月本店）平均分配</a-button>
          </div>
        </template>
        <p v-else class="wraningColor"> 没有销售数据，不支持智能分配 </p>
      </div>
      <div>
        <p>
          <span>剩余: </span>
          <span style="font-size: 20px"> {{ countRemaingFee() }}</span>
        </p>
        <p>
          <span>月份:</span>
          <span style="font-size: 20px"> {{ allocDialog.item.month }}</span>
        </p>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { onMounted, ref, computed, reactive, PropType } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { FilterTableItem, ExportInfo } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import useBaseDataStore from '@/store/modules/base-data'
  import { SettlementItemFind, AmzSettlementAllocItemFind, AmzSettlementFeeAllocItemAgg, saveSettlementItemSku, saveSettlementItemSalesman, saveSettlementItemSumType, saveSettlementItemManualAllocStatus, saveSettlementFeeAllocItem, saveSettlementFeeAllocManual, AmzSettlementSettlementReservedStatus, FindShopId, FindShopUsers, SalesAmountAggBySellerInfo } from '@/api/finance/summaryReport'
  import { getStartAndEndTime } from '@/utils/timeFormat'
  import dayjs from 'dayjs'
  import { marketPlaceList } from '@/utils/globalData'
  import useUserStore from '@/store/modules/user'
  import ChooseUser from '@/components/ChooseUser.vue'
  import ChooseProduct from '@/components/ChooseProduct.vue'
  import { settlementItemSheet } from '@/utils/exportFiled'

  onMounted(() => {
    setDefaultSearch()
    getUserList()
  })
  const emit = defineEmits(['toSearch'])
  const exportInfo: ExportInfo = {
    title: '结算报告明细',
    type: 'single',
    supportAll: true,
    tabName: '结算报告明细',
    fieldList: settlementItemSheet,
    supportTemplate: true,
    templateType: 'SETTLEMENT_ITEM_LIST',
    exportApi: 'exportSettlementItem',
    excelName: '结算明细报告',
  }
  const props = defineProps({
    searchVal: {
      type: Object,
      default: () => {},
    },
    markedtList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    shopList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
  })
  const searchVal = ref<any>({})
  const filterData = ref<any>({
    ...props.searchVal,
  })
  const tableLoading = ref(false)
  const useBaseData = useBaseDataStore()
  const tableList = ref<Array<any>>([])
  const userList = ref<Array<any>>([])
  const tableListMap = ref({})
  const selectIds = ref([])
  const userStore = useUserStore()
  const tableRef = ref()
  const showUserDialog = ref(false)
  const isNotSalesman = ref(false)
  const showChooseProductDialog = ref(false)
  const isNotSumType = ref(false)
  const total = ref(0)
  const updateSumType = ref<any>()
  const seachData = ref<any>({})
  const allocDialog = ref<any>({
    salesamountList: [],
    allow_items: [],
  })
  const sumTypesList = [
    {
      label: '订阅费',
      value: 'SUBSCRIPTION_FEE',
    },
    {
      label: '广告费',
      value: 'ADVERTISING_EXPENSES',
    },
    {
      label: '交易费',
      value: 'TRANSACTION_FEE',
    },
    {
      label: '秒杀费',
      value: 'SECKILL_FEE',
    },
    {
      label: '运费',
      value: 'TRANSPORTATION_EXPENSES',
    },
    {
      label: '退货金额',
      value: 'RETURN_AMOUNT',
    },
    {
      label: '销售金额',
      value: 'SALES_AMOUNT',
    },
    {
      label: '上期预留金',
      value: 'LAST_RESERVED_AMOUNT',
    },
    {
      label: '本期预留金',
      value: 'THIS_RESERVED_AMOUNT',
    },
    {
      label: '优惠金额',
      value: 'PREFERENTIAL_AMOUNT',
    },
    {
      label: '月租费',
      value: 'MONTHLY_RENT',
    },
    {
      label: '其他费用',
      value: 'OTHER_EXPENSES',
    },
    {
      label: '评论费',
      value: 'COMMENT_FEE',
    },
    {
      label: '税费',
      value: 'CASH_WITHDRAWAL_AMOUNT',
    },
  ]
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
  }) as any
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplace_id_list',
      label: '站点',
      value: ref(props.searchVal.marketplace_id_list ? props.searchVal.marketplace_id_list?.split(',') : null),
      type: 'select_multiple',
      width: 120,
      optionItems: props.markedtList?.map((el: any) => {
        return {
          label: el.marketplaceName,
          value: el.marketplaceId,
        }
      }),
    },
    {
      key: 'seller_id_list',
      label: '全部店铺',
      value: ref(props.searchVal?.seller_id_list ? props.searchVal.seller_id_list.split(',') : null),
      type: 'select_multiple',
      width: 120,
      optionItems: props.shopList?.map((el: any) => {
        return {
          label: el.shopName,
          value: el.sellerId,
        }
      }),
    },
    {
      key: 'settlement_id',
      label: '结算ID',
      value: ref(props.searchVal.settlement_id),
      type: 'input_search',
      width: 180,
    },
    {
      key: 'salesman_id',
      label: '运营',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [],
    },

    {
      key: 'order_id',
      label: '订单号',
      value: ref(),
      type: 'input_search',
      width: 180,
    },
    {
      type: 'keyword_date_range',
      key: 'settlementEnd',
      keyItems: [
        { label: '结算开始时间', value: 'settlementStart' },
        { label: '结算结束时间', value: 'settlementEnd' },
        { label: '发布时间', value: 'post' },
      ],
      keyWidth: '130',
      value: ref(props.searchVal.settlement_id ? null : getStartAndEndTime('this_month', 'YYYY-MM-DD HH:mm:ss')),
      placeholder: '请输入',
      label: '结算结束时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },

    {
      key: 'transactionTypes',
      label: '交易类型',
      value: ref(),
      type: 'select_multiple',
      width: 100,
      optionItems: [
        { label: 'Order', value: 'Order' },
        { label: 'Refund', value: 'Refund' },
        { label: 'other-transaction', value: 'other-transaction' },
        { label: 'TBYB Order Payment', value: 'TBYB Order Payment' },
        { label: 'TBYB Trial Shipment', value: 'TBYB Trial Shipment' },
        { label: 'ServiceFee', value: 'ServiceFee' },
        { label: 'Liquidations', value: 'Liquidations' },
        { label: 'Liquidations Adjustments', value: 'Liquidations Adjustments' },
        { label: 'Lighting Deal Fee', value: 'Lighting Deal Fee' },
        { label: 'CouponRedemptionFee', value: 'CouponRedemptionFee' },
        { label: 'Vine Enrollment Fee', value: 'Vine Enrollment Fee' },
        { label: 'Chargeback Refund', value: 'Chargeback Refund' },
        { label: 'A-to-z Guarantee Refund', value: 'A-to-z Guarantee Refund' },
      ],
    },
    {
      key: 'amountTypes',
      label: '金额类型',
      value: ref(),
      type: 'select_multiple',
      width: 100,
      optionItems: [
        {
          label: 'ItemPrice',
          value: 'ItemPrice',
        },
        {
          label: 'ItemFees',
          value: 'ItemFees',
        },
        {
          label: 'Promotion',
          value: 'Promotion',
        },
        {
          label: 'Cost of Advertising',
          value: 'Cost of Advertising',
        },
        {
          label: 'other-transaction',
          value: 'other-transaction',
        },
        {
          label: 'Lighting Deal Fee',
          value: 'Lighting Deal Fee',
        },
        {
          label: 'FBA Inventory Reimbursement',
          value: 'FBA Inventory Reimbursement',
        },
        {
          label: 'CouponRedemptionFee',
          value: 'CouponRedemptionFee',
        },
        {
          label: 'ItemWithheldTax',
          value: 'ItemWithheldTax',
        },
        {
          label: 'Vine Enrollment Fee',
          value: 'Vine Enrollment Fee',
        },
        {
          label: 'Amazon Fees',
          value: 'Amazon Fees',
        },
        {
          label: 'Refund for Advertiser',
          value: 'Refund for Advertiser',
        },
      ],
    },
    {
      key: 'sum_type_list',
      label: '汇总类型',
      value: ref(),
      type: 'select_multiple',
      width: 100,
      optionItems: sumTypesList,
    },

    {
      key: 'sellerSku',
      label: 'SellerSKU',
      value: ref(),
      type: 'input_search',
      width: 140,
    },
    {
      key: 'productSku',
      label: '产品SKU',
      value: ref(),
      type: 'input_search',
      width: 140,
    },
    {
      key: 'amountDescription',
      label: '金额说明',
      value: ref(),
      type: 'input_search',
      width: 140,
    },
  ])
  const isAdmin = computed(() => userStore.admin)

  // 初始化查询
  function setDefaultSearch() {
    filterData.value = {
      marketplace_id_list: props.searchVal.marketplace_id_list,
      seller_id_list: props.searchVal.seller_id_list,
      settlement_id: props.searchVal.settlement_id,
    }
    if (!props.searchVal.settlement_id) {
      filterData.value.dataType = 'settlementEnd'
      filterData.value.startDate = getStartAndEndTime('this_month', 'YYYY-MM-DD HH:mm:ss')?.[0]
      filterData.value.endDate = getStartAndEndTime('this_month', 'YYYY-MM-DD HH:mm:ss')?.[1]
    }
    getTableList()
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    userList.value = useBaseData.userList
    filterItem.value[3].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 显示店铺
  function oneShopName(row: any) {
    return props.shopList.find((item: any) => item.sellerId === row.seller_id)?.shopName || '未知'
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.currentPage = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.currentPage = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 设置查询条件
  function setSearchval() {
    let _params: any = JSON.parse(JSON.stringify(filterData.value))
    _params.marketplace_id_list = _params.marketplace_id_list ? _params.marketplace_id_list?.split(',') : []
    _params.seller_id_list = _params.seller_id_list ? _params.seller_id_list?.split(',') : []
    _params.sum_type_list = _params.sum_type_list ? _params.sum_type_list?.split(',') : []

    // 非管理员未选择店铺时默认传所有店铺
    if (!isAdmin.value && _params.seller_id_list?.length === 0) {
      _params.seller_id_list = props.shopList?.map((item: any) => item.sellerId) || []
      if (!_params.seller_id_list?.length) {
        Message.error('请选择店铺')
        return
      }
    }

    if (_params.status === '1') {
      _params.status_done = true
    } else if (_params.status === '-1') {
      _params.status_process = true
    }
    if (_params.startDate && _params.endDate) {
      let startStr = _params.dataType == 'post' ? 'StartDate' : 'DateStart'
      let endStr = _params.dataType == 'post' ? 'EndDate' : 'DateEnd'
      _params[`${_params.dataType}${startStr}`] = dayjs(_params.startDate).unix()
      _params[`${_params.dataType}${endStr}`] = dayjs(_params.endDate).unix()
    }
    delete _params.startDate
    delete _params.endDate
    delete _params.dataType

    _params.isNotSalesman = isNotSalesman.value ? true : false
    _params.isNotSumType = isNotSumType.value ? true : false
    return _params
  }
  // 获取商品列表
  async function getTableList() {
    tableLoading.value = true
    tableList.value = []
    const _param = {
      needCount: true,
      pageSize: searchVal.value.pageSize,
      currentPage: searchVal.value.currentPage,
      param: setSearchval(),
    }
    tableRef.value.selectAll(false)
    const res: any = await SettlementItemFind(_param)
    seachData.value = _param.param
    emit('toSearch', filterData.value)
    tableLoading.value = false
    let list = res?.data?.rs?.result || []
    total.value = res?.data?.rs?.rows || 0
    tableListMap.value = {}
    list.forEach((item: any) => {
      item.alloc_item_summary = ''
      item.need_alloc = false
      item.reserved_status = -1
      item.id = item?.seller_id + item?.settlement_id + item?.item_index
      tableListMap.value[item.id] = item
    })
    tableList.value = list
    getFeeAllocItemAgg(list)
  }
  // 加载分配数据
  async function getFeeAllocItemAgg(list: Array<any>) {
    let map = {}
    let newList = list.filter((item: any) => {
      let codes = [
        'other-transaction.other-transaction.previous-reserve-amount-balance',
        'other-transaction.other-transaction.current-reserve-amount',
        'other-transaction.other-transaction.storage-fee',
        'other-transaction.other-transaction.storagerenewalbilling',
        'other-transaction.other-transaction.subscription-fee',
        'other-transaction.other-transaction.payable-to-amazon',
        'other-transaction.other-transaction.removalcomplete',
        'other-transaction.other-transaction.disposalcomplete',
      ]
      return codes.includes(item.sum_type_code) || item.sum_type === 'OTHER_EXPENSES'
    })
    newList.forEach((item: any) => {
      map[item.settlement_id] = item.settlement_id
      item['need_alloc'] = true
    })
    let settlementIdList = Object.keys(map)
    if (settlementIdList.length === 0) return

    const res: any = await AmzSettlementFeeAllocItemAgg({
      param: {
        settlement_id_list: settlementIdList,
      },
      needCount: false,
      pageSize: 1000,
      currentPage: 1,
    })
    let feeList = res?.data?.rs?.result || []
    let map2 = {}
    feeList.forEach((item: any) => {
      let key = item.seller_id + item.settlement_id + item.settlement_start_date + item.item_index
      map2[key] = item
    })

    const rs: any = await AmzSettlementSettlementReservedStatus({
      param: {
        settlement_id_list: settlementIdList,
      },
      needCount: false,
      pageSize: 1000,
      currentPage: 1,
    })
    let list2 = rs?.data?.rs?.result || []
    let reservedmap = {}
    list2.forEach((item: any) => {
      reservedmap[item?.seller_id + item?.settlement_id + item?.item_index] = item
    })

    tableList.value.forEach((item: any) => {
      let key = item.seller_id + item.settlement_id + item.settlement_start_date + item.item_index
      let key2 = item?.seller_id + item?.settlement_id + item?.item_index
      if (map2[key]) {
        item['alloc_item_summary'] = map2[key]?.alloc_item
      }
      if (reservedmap[key2]) {
        item['reserved_status'] = reservedmap[key2]?.status || -1
      }
    })
  }
  // 打开分配
  async function onShowAllocDialog(item: any) {
    allocDialog.value.show = true
    allocDialog.value.loading = true
    allocDialog.value.item = item
    allocDialog.value.allow_items = []
    let param = {
      settlement_id: item.settlement_id,
      seller_id: item.seller_id,
      settlement_start_date: item.settlement_start_date,
      settlement_end_date: item.settlement_end_date,
      item_index: item.item_index,
    }
    const rs: any = await AmzSettlementAllocItemFind({ param: param, needCount: false, pageSize: 1000, currentPage: 1 })
    let allocedList = rs?.data?.rs?.result || []

    const res: any = await FindShopId({
      param: {
        market_id: item.marketplace_id,
        seller_id: item.seller_id,
      },
      needCount: false,
      pageSize: 1000,
      currentPage: 1,
    })
    let shopId = res?.data?.rs?.result?.[0]?.shop_id || ''

    const user: any = await FindShopUsers({
      param: {
        shop_id: shopId,
      },
      needCount: false,
      pageSize: 1000,
      currentPage: 1,
    })
    let userList = user?.data?.rs?.result || []
    userList.forEach((item: any) => {
      if (!allocedList.find((t: any) => t.salesman_id === item.user_id)) {
        allocedList.push({
          alloc_amount: 0,
          salesman_name: item.user_name,
          salesman_id: item.user_id,
        })
      }
    })
    //bugfix有用户ID，但是没有名字的情况
    allocedList.forEach((item: any) => {
      if (!item.salesman_name) {
        item.salesman_name = userList.find((el: any) => el.user_id === item.salesman_id)?.user_name || '未知名字'
      }
    })

    allocDialog.value.allow_items = allocedList

    //查找销售额
    const _result: any = await SalesAmountAggBySellerInfo({
      param: {
        seller_id: item.seller_id,
        month: item.month,
        marketplace_id: item.marketplace_id,
      },
    })

    let salesamountList = _result?.data?.rs?.result || []
    let totalAmountNeedAlloc = allocDialog.value.item.amount
    if (salesamountList.length > 0) {
      let totalAmount = salesamountList.map((item: any) => item.total_cny_amount).reduce((a: number, b: number) => a + b, 0)
      salesamountList.forEach((item: any) => {
        item['alloc_percent_amount'] = parseFloat((totalAmountNeedAlloc * (item.total_cny_amount / totalAmount)).toFixed(2))
        item['alloc_avg_amount'] = parseFloat((totalAmountNeedAlloc / salesamountList.length).toFixed(2))
      })

      let tmpamt = salesamountList.map((item: any) => item.alloc_percent_amount).reduce((a: number, b: number) => a + b, 0)
      if (tmpamt != totalAmountNeedAlloc) {
        salesamountList[0]['alloc_percent_amount'] = parseFloat((salesamountList[0]['alloc_percent_amount'] + (totalAmountNeedAlloc - tmpamt)).toFixed(2))
      }

      tmpamt = salesamountList.map((item: any) => item.alloc_avg_amount).reduce((a: number, b: number) => a + b, 0)
      if (tmpamt != totalAmountNeedAlloc) {
        salesamountList[0]['alloc_avg_amount'] = parseFloat((salesamountList[0]['alloc_avg_amount'] + (totalAmountNeedAlloc - tmpamt)).toFixed(2))
      }
    }
    allocDialog.value.salesamountList = salesamountList
    allocDialog.value.loading = false
  }

  function allocItemStatus(item: any) {
    if (item.alloc_item_summary) {
      let amt1 = item.alloc_item_summary
        ?.split(',')
        .map((el: any) => parseFloat(el.split(':')[1]))
        .reduce((a: number, b: number) => a + b, 0)
      if (amt1?.toFixed(2) === item.amount?.toFixed(2)) {
        return item.manual_alloc_status === 1 ? 'manual_alloc' : ''
      } else {
        return 'alloc_fail'
      }
    }
    return ''
  }
  // 剩余分配额度
  function countRemaingFee() {
    let totalAmt = allocDialog.value?.item?.amount || 0
    allocDialog.value?.allow_items?.forEach((item: any) => {
      if (item?.alloc_amount) {
        totalAmt -= item?.alloc_amount
      }
    })
    return totalAmt.toFixed(2)
  }
  // 自动分配
  function onAutoAlloc(type: number) {
    if (type === 1) {
      allocDialog.value.allow_items.forEach((item: any) => {
        let amount = allocDialog.value.salesamountList
          ?.filter((a: any) => a.salesman_id === item.salesman_id)
          .map((a: any) => a.alloc_percent_amount)
          .reduce((a: number, b: number) => a + b, 0)
        item.alloc_amount = amount
      })
    } else {
      //均分
      allocDialog.value.allow_items.forEach((item: any) => {
        let amount = allocDialog.value.salesamountList
          ?.filter((a: any) => a.salesman_id === item.salesman_id)
          .map((a: any) => a.alloc_avg_amount)
          .reduce((a: number, b: number) => a + b, 0)
        item.alloc_amount = amount
      })
    }
  }
  // 保存分配
  async function onReFeeAlloc() {
    let num = Number(countRemaingFee() || 0)
    if (num !== 0) {
      Message.error('金额未分配完毕！')
      return false
    }
    allocDialog.value.allow_items.forEach((item: any) => {
      item['settlement_id'] = allocDialog.value.item?.settlement_id
      item['seller_id'] = allocDialog.value.item?.seller_id
      item['month'] = allocDialog.value.item?.month
      item['settlement_end_date'] = allocDialog.value.item?.settlement_end_date
      item['settlement_start_date'] = allocDialog.value.item?.settlement_start_date
      item['currency'] = allocDialog.value.item?.currency
      item['amount_description'] = allocDialog.value.item?.amount_Description
      item['sum_type'] = allocDialog.value.item?.sum_type
      item['sum_type_name'] = allocDialog.value.item?.sum_type_name
      item['item_index'] = allocDialog.value.item?.item_index
      item['marketplace_id'] = allocDialog.value.item?.marketplace_id
    })
    let res = await saveSettlementFeeAllocManual({
      param: {
        param: {
          seller_id: allocDialog.value.item?.seller_id,
          settlement_id: allocDialog.value.item?.settlement_id,
          settlement_start_date: allocDialog.value.item?.settlement_start_date,
          settlement_end_date: allocDialog.value.item?.settlement_end_date,
          item_index: allocDialog.value.item?.item_index,
          manual_set: 1,
        },
      },
    })
    if (!res) return false

    let refs = await saveSettlementFeeAllocItem({ param: { list: allocDialog.value.allow_items } })
    if (!refs) return false

    let items = [
      {
        settlement_id: allocDialog.value.item?.settlement_id,
        seller_id: allocDialog.value.item?.seller_id,
        settlement_end_date: allocDialog.value.item?.settlement_end_date,
        settlement_start_date: allocDialog.value.item?.settlement_start_date,
        item_index: allocDialog.value.item?.item_index,
        manual_alloc_status: 1,
      },
    ]
    const rs: any = await saveSettlementItemManualAllocStatus({ param: { list: items } })
    if (!rs) return false
    Message.success('保存成功')
    allocDialog.value.show = false
    return
  }
  // 打开搜索产品
  function openChooseProductDialog() {
    if (!selectIds.value.length) {
      Message.error('请选择报告！')
      return
    }
    showChooseProductDialog.value = true
  }
  // 设置产品
  async function chooseProduct(product: any) {
    console.log(product)
    let items = selectIds.value.map((id: string) => {
      let _data = tableListMap.value[id] || {}
      return {
        settlement_id: _data.settlement_id,
        seller_id: _data.seller_id,
        settlement_end_date: _data.settlement_end_date,
        settlement_start_date: _data.settlement_start_date,
        item_index: _data.item_index,
        product_sku: product?.sku,
      }
    })
    const res: any = await saveSettlementItemSku({ param: { list: items } })
    if (res) {
      Message.success('成功绑定产品SKU！')
      getTableList()
      showChooseProductDialog.value = false
    }
  }

  // 打开设置运营
  function openShowUserDialog() {
    if (!selectIds.value.length) {
      Message.error('请选择报告！')
      return
    }
    showUserDialog.value = true
  }
  // 保存运营
  async function editSales(user: any) {
    let items = selectIds.value.map((id: string) => {
      let _data = tableListMap.value[id] || {}
      return {
        settlement_id: _data.settlement_id,
        seller_id: _data.seller_id,
        settlement_end_date: _data.settlement_end_date,
        settlement_start_date: _data.settlement_start_date,
        item_index: _data.item_index,
        salesman_id: user.id,
        salesman_name: user.userName,
      }
    })
    const res: any = await saveSettlementItemSalesman({ param: { list: items } })
    if (res) {
      Message.success('保存成功')
      getTableList()
    }
  }
  // 设置汇款类型
  async function onUpdateSumType() {
    if (!selectIds.value.length) {
      Message.error('请选择报告！')
      return
    }
    if (!updateSumType.value?.value) {
      Message.error('请选择汇总类型!')
      return
    }
    let items = selectIds.value.map((id: string) => {
      let _data = tableListMap.value[id] || {}
      return {
        settlement_id: _data.settlement_id,
        seller_id: _data.seller_id,
        settlement_end_date: _data.settlement_end_date,
        settlement_start_date: _data.settlement_start_date,
        item_index: _data.item_index,
        sum_type: updateSumType.value.value,
        sum_type_name: updateSumType.value.label,
      }
    })
    const res: any = await saveSettlementItemSumType({ param: { list: items } })
    if (res) {
      updateSumType.value = null
      Message.success('保存成功，刷新看效果')
      getTableList()
    }
  }
</script>

<style lang="less" scoped>
  .settlement-report-list {
    height: calc(100vh - @menuAndTabHeight);
  }
  .mini-btn {
    font-size: 10px;
    padding: 2px 5px;
    background-color: #fff;
    border: 1px solid #ddd;
  }
</style>
